package fuzion24.device.vulnerability.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONObject;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import fuzion24.device.vulnerability.test.VulnerabilityTestResult;
import fuzion24.device.vulnerability.util.DeviceInfo;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityOrganizer;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityResultSerialzier;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;

/**
 * Created by fuzion24 on 11/25/15.
 */
public class ScanRunnerBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "ScanRunnerReceiver";

    /*
        Example usage
        adb shell am broadcast -a com.android.vts.RUN_SCAN --es RESULT_PATH /sdcard/vts_out -n com.nowsecure.android.vts/fuzion24.device.vulnerability.broadcastreceiver.ScanRunnerBroadcastReceiver

     */
    @Override
    public void onReceive(final Context context, Intent intent) {

        Log.d(TAG, "Received broadcast for scanrunner");
        //Only allow this code to be ran on debug builds, since it accepts and writes to arbitrary file
        //paths, which would allow another app to arbitrarily write anywhere in this app's context.
        // http://android-developers.blogspot.com/2010/09/securing-android-lvl-applications.html
        boolean isDebuggable = ( 0 != ( context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) );
        if(!isDebuggable){
            Log.d(TAG, "Not running the tests because the app is not debuggable");
            return;
        }

        Bundle intentExtras = intent.getExtras();
        if(intentExtras == null){
            Log.d(TAG, "There were no extras with the broadcast. Include RESULT_PATH");
            return;
        }

        final String writeResultPath = intentExtras.getString("RESULT_PATH");
        if(writeResultPath == null || writeResultPath.equals("")){
            Log.d(TAG, "Result write path is null or empty");
        }

        Log.d(TAG, "Results will be written to: " + writeResultPath);

        new AsyncTask<Void,Void,Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                List<VulnerabilityTest> tests = VulnerabilityOrganizer.getTests(context);
                List<VulnerabilityTestResult> results = new ArrayList<>();
                for(VulnerabilityTest vt : tests){
                    Log.d(TAG, "Running: " + vt.getCVEorID());
                    boolean vulnerable = false;
                    Exception x = null;
                    try {
                        vulnerable = vt.isVulnerable(context);
                    }catch(Exception e){
                      x = e;
                    }
                    results.add(new VulnerabilityTestResult(vt, vulnerable, x));
                }

                try {
                    JSONObject jobj = VulnerabilityResultSerialzier.serializeResultsToJson(results, DeviceInfo.getDeviceInfo());
                    FileOutputStream fos = new FileOutputStream(writeResultPath);
                    fos.write(jobj.toString(2).getBytes());
                    fos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }

                return null;
            }
        }.execute();

    }
}
